//
//  WKOnlinePayVC.m
//  V-Learn
//
//  Created by Apple on 2019/3/13.
//  Copyright © 2019 yxk. All rights reserved.
//

#import "WKOnlinePayVC.h"
#import "FZXPayCell.h"
#import "WXApi.h"

#import "LBCardQuanVC.h"

#import "LBWechatPayRequestModel.h"
#import "VKVoucherController.h"

#import "LBPaySuccessVC.h"
#import "LBPayFaileVC.h"
#import "LBEvaluationResultVC.h"
#import "LBOnlineVC.h"
#define defaultTag 20191
@interface WKOnlinePayVC ()<UITableViewDelegate,UITableViewDataSource,LBCardQuanVCDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) NSInteger btnTag;//默认选中的Tag
@property (nonatomic, assign) BOOL isYueOrZhifubao;//优惠券
@property (nonatomic, strong) NSString *payType;//支付类型 1  支付宝  2 微信
@property (nonatomic, strong) NSString *quanhouPrice;//优惠后的价格
@property (nonatomic, strong) LBCardquanModel *cardquanModel;
@property (nonatomic, strong) UILabel *selectLab;
@property (nonatomic, strong) NSString *orderNum;//支付宝支付成功后保存
@property (nonatomic, strong) NSString *moneyString;

@end

@implementation WKOnlinePayVC
- (UILabel *)selectLab{
    if (!_selectLab) {
        _selectLab = [UILabel labelWithText:@"请选择" andTextColor:rgb(101,101,101) andName:nil andFontSize:15];
    }
    return _selectLab;
}
- (void)setupFengexian{
    //设置tableView 分割线不到边
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"兑换";
    self.btnTag = defaultTag+0;
    //区分是支付宝支付  还是 余额 支付
    self.isYueOrZhifubao = YES;
    
    [self setupUI];
    [self setupFengexian];
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)setupUI{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, LBNAVBAR_HEIGHT, ScreenW, ScreenH-LBNAVBAR_HEIGHT) style:UITableViewStylePlain];
    self.tableView.backgroundColor = rgb(242,242,242);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollEnabled = NO;
    [self.view addSubview:self.tableView];
    if (@available(iOS 11.0, *)) {
        
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    UIView *footerView = [UIView new];
    footerView.backgroundColor = rgb(242,242,242);
    //底部视图
    self.tableView.tableFooterView = footerView;
    footerView.frame = CGRectMake(0, 0, ScreenW, 300);
    [self.view addSubview:self.tableView];
    
    UIButton *payButton = [[UIButton alloc] init];
    [self.view addSubview:payButton];
    payButton.layer.cornerRadius = 22;
    payButton.layer.masksToBounds = YES;
    [payButton makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(44);
        make.bottom.mas_equalTo(-50);
    }];
    [payButton setTitle:@"确认兑换" forState:UIControlStateNormal];
    [payButton setTitleColor:rgb(255,255,255) forState:UIControlStateNormal];
    payButton.titleLabel.font = LBFont(18);

    [payButton setBackgroundImage:LBImage(@"wk_pay_button") forState:UIControlStateNormal];
    [payButton addTarget:self action:@selector(clickzhiFuBtn:) forControlEvents:UIControlEventTouchUpInside];

    UILabel *firstLab = [UILabel labelWithText:@"・你在该iOS设备进行虚拟币充值及消费;" andTextColor:rgb(102, 102, 102) andName:nil andFontSize:12];
    [footerView addSubview:firstLab];
    [firstLab makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.top.mas_equalTo(0);
    }];
    
    UILabel *secodLab = [UILabel labelWithText:@"・充值余额仅限iOS系统消费，无法在其他系统使用;" andTextColor:rgb(102, 102, 102) andName:nil andFontSize:12];
    [footerView addSubview:secodLab];
    [secodLab makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(firstLab.mas_bottom).mas_equalTo(5);
        make.left.mas_equalTo(15);
    }];
    
    UILabel *thirdLab = [UILabel labelWithText:@"・充值余额和消费不可转让、退换和申请发票!" andTextColor:rgb(102, 102, 102) andName:nil andFontSize:12];
    [footerView addSubview:thirdLab];
    [thirdLab makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(secodLab.mas_bottom).mas_equalTo(5);
        make.left.mas_equalTo(15);
    }];
}
- (void)clickPayBtn:(UIButton *)sender{
    LBPayFaileVC *paySuccessVC = [LBPayFaileVC new];
    [self.navigationController pushViewController:paySuccessVC animated:YES];
}
- (void)clickzhiFuBtn:(UIButton *)sender{
//    NSLog(@"去支付");
    
    [self dealWithOrderPay];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getGold];
}
- (void)getGold{
    [WYHXNetWorkManager post:WKCheckMoney_WKURL params:@{@"token":[UserModel getUserModel].token} completionHandler:^(id responseObj, NSError *error) {
        NSString *code = responseObj[@"code"];
        if ([code integerValue]==200) {
            NSLog(@"%@",responseObj);
            
            //保存余额
            NSString *string = [NSString stringWithFormat:@"%@",responseObj[@"data"][@"userMoney"]];
            self.moneyString = string;
        }
        [self.tableView reloadData];
    }];
}
// 发起支付请求
- (void)dealWithOrderPay {
    // 业务逻辑，先向服务器发起预支付请求，服务器返回支持订单信息。
    // ...
    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    NSString *token = [UserModel getUserModel].token;

    //WKWechatPay_WKURL
    //乐学币  WKCoursePay_WKURL
    NSString *userMoney = self.moneyString;//[[NSUserDefaults standardUserDefaults] objectForKey:@"userMoney"];
    //判断当前用户余额是否大于当前课程价格  小于 去充值
    if ([userMoney integerValue]<[self.price integerValue]) {
//        [MBProgressHUD showSuccess:@"余额不足" toView:self.view];
//        return;
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"余额不足" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"去充值" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //这里来个弹框是否去充值
            MoneyViewController *moneyVC = [[MoneyViewController alloc] init];
            [self.navigationController pushViewController:moneyVC animated:YES];
            
        }]];
        [self presentViewController:alertController animated:YES completion:nil];

    }else{
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"网课不退费，谨慎购买" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            
            [data setObject:token forKey:@"token"];
            [data setObject:self.tel forKey:@"tel"];
            [data setObject:self.ageYear forKey:@"ageYear"];
            [data setObject:self.ageMonth forKey:@"ageMonth"];
            [data setObject:self.courseLength forKey:@"courseLength"];
            [data setObject:self.planType forKey:@"planType"];
            [data setObject:self.price forKey:@"price"];

            //WKonLinePlanFromGold_WKURL  新接口
            //WKguihuaAnddingzhiPay_WKURL  旧接口
            [WYHXNetWorkManager post:WKonLinePlanFromGold_WKURL params:data completionHandler:^(id responseObj, NSError *error) {
                //        NSLog(@"%@",responseObj);
                NSDictionary *data = responseObj[@"data"];
                NSString *code = responseObj[@"code"];
                NSString *msg = responseObj[@"msg"];
                if ([code integerValue]==200) {
                    if (self.orderNum) {
                        [[NSUserDefaults standardUserDefaults] setObject:self.orderNum forKey:@"orderNum"];
                        [[NSUserDefaults standardUserDefaults] synchronize];
                    }
                    
                    for(UIViewController *controller in self.navigationController.viewControllers) {
                        if([controller isKindOfClass:[LBEvaluationResultVC class]]) {
                            [self.navigationController popToViewController:controller animated:YES];
                        }
                    }
                    for(UIViewController *controller in self.navigationController.viewControllers) {
                        if([controller isKindOfClass:[LBOnlineVC class]]) {
                            [self.navigationController popToViewController:controller animated:YES];
                        }
                    }
                }else{
                    [MBProgressHUD showSuccess:msg toView:self.view];
                }
                
            }];
            
        }]];
        
        [self presentViewController:alertController animated:YES completion:nil];
        
        
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return 2;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.section==0) {
        UILabel *nameLab = [UILabel labelWithText:@"" andTextColor:nil andName:nil andFontSize:15*kScaleFit];
        [cell.contentView addSubview:nameLab];
        [nameLab makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(-15*kScaleFit);
            make.centerY.mas_equalTo(cell.contentView);
        }];
        if (indexPath.row==0) {
            cell.textLabel.text = @"名称";
            cell.textLabel.textColor = rgb(51,51,51);
            
//            if ([self.planType isEqualToString:@"2"]) {
//                nameLab.text = self
//            }else{
//                nameLab.text = self.model.courseName;//@"课程名称";
//            }
            nameLab.text = self.titleString;
            nameLab.textColor = rgb(101,101,101);
        }
        if (indexPath.row==1) {
            cell.textLabel.text = @"价格";
            cell.textLabel.textColor = rgb(51,51,51);
            
//            if ([self.type isEqualToString:@"2"]) {
//                nameLab.text = self.packModel.data.packagePrice;//@"¥100";
//            }else{
            nameLab.text = self.price;//@"¥100";
//            }
            /**
             else if ([self.type isEqualToString:@"3"]){
             //点击优惠券后的赋值
             nameLab.text = self.quanhouPrice;
             }
             */
            nameLab.textColor = rgb(233,38,18);
        }

        cell.textLabel.font = LBFont(15*kScaleFit);
        return cell;
        
    }
    
    return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (section==0) {
        return nil;
    }else{
        UIView *headerView = [UIView new];
        //竖线
        UIView *lineView=[UIView new];
        lineView.backgroundColor = rgb(233,84,18);
        [headerView addSubview:lineView];
        [lineView makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(15*kScaleFit);
            make.bottom.mas_equalTo(-10*kScaleFit);
            make.size.mas_equalTo(CGSizeMake(2*kScaleFit, 15*kScaleFit));
        }];
        
        UILabel *payTypeLab = [UILabel labelWithText:@"支付方式" andTextColor:rgb(40,40,40) andName:nil andFontSize:15*kScaleFit];
        [headerView addSubview:payTypeLab];
        [payTypeLab makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(lineView.mas_right).mas_equalTo(2*kScaleFit);
            make.centerY.mas_equalTo(lineView);
        }];
        headerView.backgroundColor = rgb(242,242,242);
        return headerView;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 0.001;
    }else{
        return 65*kScaleFit;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section==0) {
        UIView *headerView = [UIView new];
        
        
//        UILabel *payTypeLab = [UILabel labelWithText:@"¥29" andTextColor:rgb(233,38,18) andName:nil andFontSize:18*kScaleFit];
//        [headerView addSubview:payTypeLab];
//        payTypeLab.text = self.price;
//        [payTypeLab makeConstraints:^(MASConstraintMaker *make) {
//            make.right.mas_equalTo(-15*kScaleFit);
//            make.centerY.mas_equalTo(headerView);
//        }];
//        headerView.backgroundColor = rgb(242,242,242);
        //如果选择了优惠券，这里需要将优惠券价格 减去
        //        NSString *yuanPrice = self.model.coursePrice;
        //        NSString *youhuiPrice = @"";
        //        NSInteger totalPrice = [yuanPrice.integerValue-youhuiPrice.integerValue];
        

//        UILabel *payTypeLab2 = [UILabel labelWithText:@"合计:" andTextColor:rgb(233,38,18) andName:nil andFontSize:12*kScaleFit];
//        [headerView addSubview:payTypeLab2];
//        [payTypeLab2 makeConstraints:^(MASConstraintMaker *make) {
//            make.right.mas_equalTo(payTypeLab.mas_left).mas_equalTo(-10*kScaleFit);
//            make.centerY.mas_equalTo(headerView);
//        }];
        headerView.backgroundColor = rgb(242,242,242);
        return headerView;
    }else{
        return nil;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section==0) {
        return 10;
    }else{
        return 0;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        if (indexPath.row==2) {
            //暂时屏蔽
            [MBProgressHUD showSuccess:@"该功能暂未开放" toView:self.view];
            return;
            LBCardQuanVC *quanVC = [[LBCardQuanVC alloc] init];
            quanVC.delegate = self;
            [self.navigationController pushViewController:quanVC animated:YES];
        }
    }
}

@end
